package com.oa.config.springSecurity;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oa.entity.domain.User;
import com.oa.entity.vo.LoginUser;
import com.oa.mapper.PermissionMapper;
import com.oa.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 登录认证   修改数据查询方式
 */
@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户信息
        QueryWrapper<User>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",username);
        User user=userMapper.selectOne(queryWrapper);
        if(Objects.isNull(user)){
            throw  new RuntimeException("用户不存在或者用户名输入错误");
        }
        //TODO 查询用户对应权限信息（根据用户名查询对应权限信息，并将用户信息和权限信息封装成UserDeatis对象）
//        List<String>list=new ArrayList<>(Arrays.asList("rest","admin"));
         List<String> list = permissionMapper.selectPermByUserId(user.getId());
        if(list.size()==0){
            throw  new RuntimeException("该用户还没有授权");
        }
        //封装
        return new LoginUser(user,list);
    }
}
